import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/test',
      name: 'Test',
      component: () => import('@/pages/Test.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/pages/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layouts/MainLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Dashboard',
          component: () => import('@/pages/Dashboard.vue')
        },
        {
          path: 'orders',
          name: 'Orders',
          component: () => import('@/pages/Orders.vue')
        },
        {
          path: 'orders/sync',
          name: 'OrderSync',
          component: () => import('@/views/order/Sync.vue')
        },
        {
          path: 'import',
          name: 'Import',
          component: () => import('@/pages/Import.vue')
        },
        {
          path: 'settlement',
          name: 'Settlement',
          component: () => import('@/pages/Settlement.vue')
        },
        {
          path: 'insurance',
          name: 'Insurance',
          component: () => import('@/pages/Insurance.vue')
        },
        {
          path: 'purchase',
          name: 'Purchase',
          component: () => import('@/pages/Purchase.vue')
        },
        {
          path: 'reports',
          name: 'Reports',
          component: () => import('@/pages/Reports.vue')
        },
        {
          path: 'system/config',
          name: 'SystemConfig',
          component: () => import('@/views/system/Config.vue')
        },
        {
          path: 'system/log',
          name: 'SystemLog',
          component: () => import('@/views/system/Log.vue')
        }
      ]
    }
  ]
})

// 简化的路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫 - 目标路径:', to.path)
  
  const authStore = useAuthStore()
  console.log('路由守卫 - Token:', authStore.token)
  console.log('路由守卫 - 用户信息:', authStore.userInfo)
  console.log('路由守卫 - 认证状态:', authStore.isAuthenticated)
  console.log('路由守卫 - 登录状态:', authStore.isLoggedIn)
  
  // 如果访问登录页且已登录，跳转到首页
  if (to.path === '/login' && authStore.token) {
    console.log('已登录，跳转到首页')
    next('/')
    return
  }
  
  // 如果访问需要认证的页面但未登录，跳转到登录页
  if (to.meta.requiresAuth && !authStore.token) {
    console.log('需要认证但未登录，跳转到登录页')
    next('/login')
    return
  }
  
  // 其他情况正常跳转
  console.log('正常跳转')
  next()
})

export default router 